// src/ChangePassword.tsx
import React, { useState } from 'react';
import { Modal, Input, Button, message } from 'antd';

interface ChangePasswordProps {
  visible: boolean;
  onClose: () => void;
  username: string;
}

interface ChangePasswordRequest {
  username: string;
  currentPassword: string;
  newPassword: string;
}

const ChangePassword: React.FC<ChangePasswordProps> = ({
  visible,
  onClose,
  username
}) => {
  const [loading, setLoading] = useState(false);
  const [inputValues, setInputValues] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  const [passwordErrors, setPasswordErrors] = useState({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  const changePassword = async (requestData: ChangePasswordRequest): Promise<boolean> => {
    try {
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      
      const headers: HeadersInit = {
        'Content-Type': 'application/json',
      };
      
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const response = await fetch('/api/users/change-password', {
        method: 'POST',
        headers,
        body: JSON.stringify(requestData),
      });

      if (response.ok) {
        return true;
      } else {
        let errorMessage = '密码修改失败';
        
        try {
          const errorData = await response.json();
          if (errorData.message) {
            errorMessage = errorData.message;
          } else if (errorData.error) {
            errorMessage = errorData.error;
          }
          
          if (errorMessage.includes('currentPassword') || errorMessage.includes('原密码') || errorMessage.includes('不正确')) {
            errorMessage = '当前密码不正确';
          }
        } catch {
          errorMessage = `服务器错误 (${response.status})`;
        }
        
        message.error(errorMessage);
        return false;
      }
    } catch (error) {
      console.error('调用密码修改接口出错:', error);
      message.error('修改密码失败，请稍后重试');
      return false;
    }
  };

  const validatePasswordForm = (): boolean => {
    const errors = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    };

    let isValid = true;

    if (!inputValues.oldPassword.trim()) {
      errors.oldPassword = '请输入当前密码';
      isValid = false;
    }

    if (!inputValues.newPassword.trim()) {
      errors.newPassword = '请输入新密码';
      isValid = false;
    }

    if (!inputValues.confirmPassword.trim()) {
      errors.confirmPassword = '请确认新密码';
      isValid = false;
    } else if (inputValues.newPassword !== inputValues.confirmPassword) {
      errors.confirmPassword = '两次输入的密码不一致';
      isValid = false;
    }

    if (inputValues.newPassword === inputValues.oldPassword) {
      errors.newPassword = '新密码不能与旧密码相同';
      isValid = false;
    }

    setPasswordErrors(errors);
    return isValid;
  };

  const handleChangePassword = async () => {
    if (!validatePasswordForm()) {
      return;
    }

    setLoading(true);

    try {
      const requestData: ChangePasswordRequest = {
        username,
        currentPassword: inputValues.oldPassword,
        newPassword: inputValues.newPassword
      };

      const success = await changePassword(requestData);

      if (success) {
        message.success('密码修改成功');
        handleClose();
      }
    } catch (error) {
      console.error('修改密码时发生错误:', error);
      message.error('修改密码时发生未知错误');
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordInputChange = (field: string, value: string) => {
    setInputValues(prev => ({ ...prev, [field]: value }));
    
    if (passwordErrors[field as keyof typeof passwordErrors]) {
      setPasswordErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  const handleClose = () => {
    setInputValues({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    setPasswordErrors({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    });
    onClose();
  };

  return (
    <Modal
      title="修改密码"
      open={visible}
      onCancel={handleClose}
      footer={null}
      width={400}
      destroyOnClose
    >
      <Input.Password
        placeholder="请输入当前密码"
        value={inputValues.oldPassword}
        onChange={(e) => handlePasswordInputChange('oldPassword', e.target.value)}
        style={{ marginBottom: 8 }}
        status={passwordErrors.oldPassword ? 'error' : ''}
      />
      {passwordErrors.oldPassword && (
        <div style={{ color: '#ff4d4f', fontSize: '12px', marginBottom: 12 }}>
          {passwordErrors.oldPassword}
        </div>
      )}

      <Input.Password
        placeholder="请输入新密码 (至少6位)"
        value={inputValues.newPassword}
        onChange={(e) => handlePasswordInputChange('newPassword', e.target.value)}
        style={{ marginBottom: 8 }}
        status={passwordErrors.newPassword ? 'error' : ''}
      />
      {passwordErrors.newPassword && (
        <div style={{ color: '#ff4d4f', fontSize: '12px', marginBottom: 12 }}>
          {passwordErrors.newPassword}
        </div>
      )}

      <Input.Password
        placeholder="请确认新密码"
        value={inputValues.confirmPassword}
        onChange={(e) => handlePasswordInputChange('confirmPassword', e.target.value)}
        style={{ marginBottom: 8 }}
        status={passwordErrors.confirmPassword ? 'error' : ''}
        onPressEnter={handleChangePassword}
      />
      {passwordErrors.confirmPassword && (
        <div style={{ color: '#ff4d4f', fontSize: '12px', marginBottom: 12 }}>
          {passwordErrors.confirmPassword}
        </div>
      )}
      
      <Button 
        type="primary" 
        block 
        loading={loading}
        onClick={handleChangePassword}
        disabled={!inputValues.oldPassword || !inputValues.newPassword || !inputValues.confirmPassword}
      >
        {loading ? '修改中...' : '确认修改'}
      </Button>
    </Modal>
  );
};

export default ChangePassword;